import JSZip from 'jszip'
import FileSaver from 'file-saver'
import axios from 'axios'
import { ElMessage } from 'element-plus'
export function initDownload(data) {
  ElMessage.success('正在下载...')
  download(data)
}

async function download(data) {
  try {
    const zip = new JSZip()
    for (let i = 0; i < data.length; i++) {
      const lst = data[i].split('.')
      const fileType = lst[lst.length - 1]
      const fileName = data[i].split('.').reverse()[1].split('/').reverse()[0]
      const fileFormat = data[i].split('.').reverse()[0].split('!')[0]
      if (fileType.toLocaleUpperCase() === 'PDF') {
        await getFile(data[i]).then(pdf => {
          zip.file('测试.pdf', pdf, {
            binary: true
          })
        })
      } else {
        await getBase64Image(data[i]).then(res => {
          zip.file(fileName + `.${fileFormat}`, res, {
            base64: true
          })
        })
      }
    }
    downImg(zip)
  } catch (err) {
    console.log('err', err)
  }
}
function downImg(zip) {
  zip
    .generateAsync({
      type: 'blob'
    })
    .then(content => {
      const fileName = '批量下载.zip'
      FileSaver.saveAs(content, fileName)
    })
}

//* ***传入图片链接，返回base64数据
function getBase64Image(url) {
  return new Promise((resolve, reject) => {
    var base64 = ''
    var img = new Image()
    img.useCORS = true // 解决跨域
    img.setAttribute('crossOrigin', 'Anonymous') // 解决跨域
    img.onload = () => {
      base64 = image2Base64(img)
      resolve(base64.split(',')[1])
    }
    img.onerror = () => reject('加载失败')
    // 这里可能会有跨域失败的问题，解决方案同上，url + 随机数
    img.src = url + '?=' + Math.random()
  })
}
function image2Base64(img) {
  var canvas = document.createElement('canvas')
  canvas.width = img.width
  canvas.height = img.height
  var ctx = canvas.getContext('2d')
  ctx.drawImage(img, 0, 0, img.width, img.height)
  var dataURL = canvas.toDataURL('image/png')
  return dataURL
}
//* ***传入文件链接，返回arraybuffer数据
function getFile(url) {
  return new Promise((resolve, reject) => {
    axios({
      method: 'get',
      url: url + '?=' + Math.random(),
      responseType: 'arraybuffer'
    })
      .then(data => {
        resolve(data.data)
      })
      .catch(error => {
        reject('PDF加载失败：' + error)
      })
  })
}
